package stark.app.function.map.amap;

import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.RoutePara;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.bar.OnTitleBarListener;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import stark.app.R;
import stark.app.databinding.ActivityAmapDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.DistanceUtil;
import stark.common.basic.utils.StatusBarUtils;

/**
 * Author：daizhongbin on 2021/9/9
 * Email：1027154338@qq.com
 * Desc:
 */
public class AmapDemoActivity extends BaseNoModelActivity<ActivityAmapDemoBinding> {

    private AMap mAmap;
    //中心点经纬度
    private LatLng mCenterLatLng;
    //我的位置的经纬度
    private LatLng mMyLatLng;
    private MyPoiOverlay mPoiOverlay;
    //正在显示的点
    private Marker mShowMarker;
    private boolean isFist = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //mapview
        mDataBinding.mapView.onCreate(savedInstanceState);
        mAmap = mDataBinding.mapView.getMap();

        //定位蓝点
        MyLocationStyle locationStyle = new MyLocationStyle();
        locationStyle.strokeColor(Color.parseColor("#00FFFFFF"));
        locationStyle.radiusFillColor(Color.parseColor("#00FFFFFF"));
        locationStyle.interval(2000);
        locationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        mAmap.setMyLocationStyle(locationStyle);
        mAmap.setMyLocationEnabled(true);

        //ui settings
        UiSettings uiSettings = mAmap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);
        uiSettings.setMyLocationButtonEnabled(true);
        uiSettings.setScaleControlsEnabled(true);

        //listener
        mAmap.addOnMyLocationChangeListener(onMyLocationChangeListener);
        mAmap.addOnCameraChangeListener(onCameraChangeListener);
        mAmap.addOnMarkerClickListener(onMarkerClickListener);
    }

    @Override
    protected int onCreate() {
        StatusBarUtils.setStatusTransparent(this);
        return R.layout.activity_amap_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View view) {
                onBackPressed();
            }

            @Override
            public void onTitleClick(View view) {
            }

            @Override
            public void onRightClick(View view) {
            }
        });
        mDataBinding.incSearch.ivSearch.setOnClickListener(v -> {
            search(mDataBinding.incSearch.atvSearch.getText().toString());
        });
        mDataBinding.incSearch.atvSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                search(s.toString());
            }
        });
        mDataBinding.incDetail.ivClose.setOnClickListener(v -> {
            mDataBinding.incDetail.containerDetail.setVisibility(View.GONE);
        });
        mDataBinding.incDetail.tvNavi.setOnClickListener(v -> {
            startNavi();
        });

    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDataBinding.mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDataBinding.mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDataBinding.mapView.onDestroy();
        mAmap.removeOnMyLocationChangeListener(onMyLocationChangeListener);
        mAmap.removeOnCameraChangeListener(onCameraChangeListener);
        mAmap.removeOnMarkerClickListener(onMarkerClickListener);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mDataBinding.mapView.onSaveInstanceState(outState);
    }

    /**
     * 通过关键字搜索
     *
     * @param keyWord
     */
    private void search(final String keyWord) {
        if (TextUtils.isEmpty(keyWord)) {
            ToastUtils.showShort("请输入要查询的酒店");
            return;
        }
        PoiSearch.Query query = new PoiSearch.Query(keyWord, "100000", "");
        query.setPageSize(100);
        query.setPageNum(0);
        //设置查周边
        if (mCenterLatLng != null) {
            PoiSearch poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult poiResult, int retCode) {
                    if (retCode != AMapException.CODE_AMAP_SUCCESS) {
                        ToastUtils.showShort("搜索失败");
                        return;
                    }
                    if (poiResult == null || poiResult.getQuery() == null) {
                        ToastUtils.showShort("对不起，没有搜索到相关数据");
                        return;
                    }

                    List<PoiItem> poiItemList = poiResult.getPois();
                    if (poiItemList == null || poiItemList.size() == 0) {
                        ToastUtils.showShort("对不起，没有搜索到相关数据");
                        return;
                    }

                    if (mPoiOverlay != null) {
                        mPoiOverlay.removeFromMap();
                    }
                    mAmap.clear();
                    mPoiOverlay = new MyPoiOverlay(mAmap, poiItemList);
                    mPoiOverlay.addToMap();
                    mPoiOverlay.zoomToSpan();
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {
                }
            });
            // 设置搜索区域为以lp点为圆心，其周围10公里范围
            LatLonPoint latLonPoint = new LatLonPoint(mCenterLatLng.latitude, mCenterLatLng.longitude);
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 10000, true));
            // 异步搜索
            poiSearch.searchPOIAsyn();
        }
    }

    private void showMarker(Marker marker) {
        mShowMarker = marker;
        mDataBinding.incDetail.containerDetail.setVisibility(View.VISIBLE);
        PoiItem poiItem = (PoiItem) marker.getObject();
        //name
        mDataBinding.incDetail.tvAddrName.setText(poiItem.getTitle());
        //distance
        float distance = poiItem.getDistance();
        if (mMyLatLng != null) {
            distance = AMapUtils.calculateLineDistance(mShowMarker.getPosition(), mMyLatLng);
        }
        mDataBinding.incDetail.tvDistance.setText(getString(R.string.distance_to_you_fmt, DistanceUtil.meter2FitStr(distance, 1)));
        //detail name
        String detailName = poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getTitle();
        String detailAddr = getString(R.string.detail_addr_fmt, detailName);
        mDataBinding.incDetail.tvAddrDetail.setText(detailAddr);
    }

    /**
     * 启动手机版高德应用进行路径规划
     */
    private void startNavi() {
        if (mShowMarker == null) return;
        try {
            RoutePara routePara = new RoutePara();
            routePara.setStartPoint(mMyLatLng);
            routePara.setStartName("我的位置");
            routePara.setEndPoint(mShowMarker.getPosition());
            routePara.setEndName(mShowMarker.getTitle());
            AMapUtils.openAMapDrivingRoute(routePara, this);
        } catch (com.amap.api.maps.AMapException e) {
            ToastUtils.showShort(e.getMessage());
        }
    }

    private AMap.OnMyLocationChangeListener onMyLocationChangeListener = new AMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if (location == null) return;
            mMyLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            if (isFist) {
                isFist = false;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                mCenterLatLng = latLng;
                float maxLevel = mAmap.getMaxZoomLevel();
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, maxLevel - 3);
                mAmap.moveCamera(cameraUpdate);
            }
        }
    };

    private AMap.OnCameraChangeListener onCameraChangeListener = new AMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
        }

        @Override
        public void onCameraChangeFinish(CameraPosition cameraPosition) {
            if (cameraPosition == null) return;
            if (cameraPosition.target != null) {
                mCenterLatLng = cameraPosition.target;
            }
        }
    };

    private AMap.OnMarkerClickListener onMarkerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            showMarker(marker);
            return true;
        }
    };
}
